package com.udf.common;

import org.apache.flink.table.functions.ScalarFunction;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class WinAlertUDF extends ScalarFunction {
    public String eval(Double input,Integer play_id) {

        if (input > 1000){
            System.out.println("hello-------");
            Alert alert = new Alert();
            alert.setPlayerId(play_id);
            alert.setTotalWin(input);
            alert.setTableName("test");
            try {
                httpGet("http://192.168.50.12:5000/send?text=",alert);
            } catch (Exception e) {
                return e.getMessage();
            }
            return String.format("%d,%s",play_id,"sum > 1000");
        }else {
            return String.format("%d,%s",play_id,"sum <= 1000");
        }
    }

    public void httpGet(String urlStr,Alert alert) throws Exception{

            String encode = URLEncoder.encode(alert.toString(), StandardCharsets.UTF_8.toString());
            URL url = new URL(urlStr+encode);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

            // 设置超时和请求头
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("User-Agent", "Java HTTP Client");

            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()))) {
                    String inputLine;
                    StringBuilder response = new StringBuilder();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    //System.out.println("Response: " + response.toString());
                }
            } else {
                System.out.println("GET request failed: " + responseCode);
            }
    }



}